package com.erpanderp.wam.ac.view.project;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import com.erpanderp.wam.ac.model.entity.project.ProjectAssignment;
import com.erpanderp.wam.ac.model.entity.project.ProjectAssignmentDetail;
import com.erpanderp.wam.ac.model.service.project.ProjectAssignmentDAO;
import com.erpanderp.wam.tm.model.service.RRFDAO;
import com.erpanderp.wam.usm.model.entity.projectandassignment.Project;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.EmployeeAndReporting;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.projectandassignment.ProjectDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;

@ManagedBean
@ViewScoped
public class CreateDomesticProjectAssignmentBean implements Serializable {

	private static final long serialVersionUID = 1L;
    
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
			.getExternalContext().getSession(true);
	HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	
	ProjectDAO projectDAO = new ProjectDAO();
	ProjectAssignmentDAO projectAssignmentDAO = new ProjectAssignmentDAO();
	RRFDAO rrfDAO = new RRFDAO();
	EmployeeAndReportingDAO employeeAndReportingDAO = new EmployeeAndReportingDAO();
	
	
	private boolean FORM_VALID;
	
	private ProjectAssignment projectAssignment = new ProjectAssignment();
	private ProjectAssignmentDetail projectAssignmentDetail = new ProjectAssignmentDetail();
	private Employee employee = new Employee();
	private EmployeeAndReporting employeeAndReporting = new EmployeeAndReporting();
	
	
	private List<Project> projects = new ArrayList<Project>();
	private Map<String, Long> projectsMap = new HashMap<String, Long>();
	
	private Long selectedProjectId;
	private Project selectedProject= new Project();
	
	private WAMUser wamUser = new WAMUser();
	private String projectAssignmentCode;
	private String employeeId;
	private String contactNumber="";
	private String approvedBy="";
	private Float advanceAmount;
	private Float roomRentAdvance;
	private Date createDate;
	private String additionals;
	String EMAIL_MESSAGE;
	
	private Employee reportingManager = new Employee();
	private Long reportingManagerId;
	private EmailUtil emailUtil = new EmailUtil();
	
	
	
	public CreateDomesticProjectAssignmentBean() 
	{
		System.out.println(selectedProjectId);
		  setWamUser((WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER));
		  projectAssignmentCode=CommonLookup.getAutoGeneratedDomesticProjectAssignmentCode(wamUser.getEmployee().getEmployeeCode());
		  System.out.println("projectAssignmentId.........."+projectAssignmentCode);
		  //Calendar currentDate = Calendar.getInstance();
		  //SimpleDateFormat formate= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
		  //String dateNow = formate.format(currentDate.getTime());
		  setCreateDate(new Date());
		  employee.setFirstName(wamUser.getEmployee().getFirstName());
		  employee.setLastName(wamUser.getEmployee().getLastName());
		  setEmployeeId(wamUser.getEmployee().getEmployeeCode());
		  setContactNumber(wamUser.getEmployee().getTelephone());
		  setApprovedBy(CommonLookup.PROJECTASSIGNMENT_DOMESTIC_INTERNATIONAL_APPROVER);
		  //reportingManager = rrfDAO.getReportingManager(wamUser.getEmployee().getEmployeeId());
		  employeeAndReporting = employeeAndReportingDAO.getEmployeeReportingDetail(wamUser.getEmployee().getEmployeeId());
		  
		  System.out.println("reportingManager.........."+employeeAndReporting);
		  //setReportingManagerId(employeeAndReporting.getProjectManager().getEmployeeId());
		   
		  projects = projectDAO.getAllProjects();
		  for(Project project :projects)
		  {
			  projectsMap.put(project.getProjectName(), project.getProjectId());
		  }
	}
	
	public void projectChangeListener(AjaxBehaviorEvent e) {
		
		if(selectedProjectId == null || selectedProjectId == 0)
		{
		
		}
		else
		{
			selectedProject = projectDAO.getProjectByProjectID(selectedProjectId);
		}
     }

	public void advanceAmountChangeListener(AjaxBehaviorEvent e){
		advanceAmount = projectAssignmentDetail.getAdvanceAmount();
		projectAssignmentDetail.setTotalAdvance(advanceAmount);
		System.out.println("bbbbbbbbbbbbbbb: " + projectAssignmentDetail.getTotalAdvance());
	
	}
	public void roomRentAdvanceChangeListener(AjaxBehaviorEvent e){
		advanceAmount = projectAssignmentDetail.getAdvanceAmount();
		roomRentAdvance = projectAssignmentDetail.getRoomRentAdvance();
		projectAssignmentDetail.setTotalAdvance(advanceAmount+roomRentAdvance);
		System.out.println("bbbbbbbbbbbbbbb: " + projectAssignmentDetail.getTotalAdvance());
	
	}
	public String saveDomesticProjectAssignmentAction() 
	{
	validateForm();
 		if(FORM_VALID){
 			    emailUtil = new EmailUtil();
 				projectAssignment.setProjectAssignmentCode(projectAssignmentCode);
 	 			projectAssignment.setCreateDate(new Date());
 	 			projectAssignmentDetail.setCreateDate(new Date());
 	 			projectAssignment.setEmployee(wamUser.getEmployee());
 	 			projectAssignment.setProject(selectedProject);
 	 			projectAssignment.setContactNumber(wamUser.getEmployee().getTelephone());
 	 			projectAssignment.setApprovedBy(CommonLookup.PROJECTASSIGNMENT_DOMESTIC_INTERNATIONAL_APPROVER);
 	 			projectAssignment.setProjectManager(employeeAndReporting.getProjectManager());
 	 			projectAssignment.setRecommendedBy(selectedProject.getOwner().getFirstName() +" "+ selectedProject.getOwner().getLastName());
 	 			projectAssignment.setProjectType(CommonLookup.PROJECT_ASSIGNMENT_TYPE_DOMESTIC);
 	 			projectAssignment.setCreatedBy(wamUser.getEmployee().getFirstName() +" "+ wamUser.getEmployee().getLastName());
 	 			projectAssignmentDetail.setCreatedBy(wamUser.getEmployee().getFirstName() +" "+ wamUser.getEmployee().getLastName());
 	 			projectAssignment.setApprovalStatus(CommonLookup.PROJECT_ASSIGNMENT_INPROCESS_STATUS);
 	 			projectAssignmentDetail.setApprovalStatus(CommonLookup.PROJECT_ASSIGNMENT_INPROCESS_STATUS);
 	 			projectAssignment.setRecommendationStatus(CommonLookup.PROJECT_ASSIGNMENT_INPROCESS_STATUS);
 	 			projectAssignmentDetail.setRecommendationStatus(CommonLookup.PROJECT_ASSIGNMENT_INPROCESS_STATUS);
 	 			projectAssignment.setStatus(CommonLookup.STATUS_ACTIVE);
 	 			projectAssignmentDetail.setStatus(CommonLookup.STATUS_ACTIVE);
 	 			projectAssignment.getProjectAssignmentDetails().add(projectAssignmentDetail);
 	 		
 	 			if(projectAssignmentDAO.createProjectAssignment(projectAssignment) != null){
 	 				System.out.println("AT CALLER METHOD: " + sendMessage());
 	 				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, projectAssignment.getProjectAssignmentId() + " ProjectAssignment created successfully.", ""));
 	 				projectAssignment = new ProjectAssignment();
 	 			}else{
 	 				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Failed to create ProjectAssignment.", ""));
 	 			}
 	 		
 			}
 		else
 		{
 			
 		}
 	System.out.println("In save ProjectAssignment");
	return null;
	}
	
	private void validateForm(){
		System.out.println("validateForm.....................");
		FORM_VALID = true;
		if(ValidationUtil.isEmpty(projectAssignment.getEmergencycontactNumber(), "Emergency Contact Number ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		System.out.println("selectedProjectId..........."+selectedProjectId);
		System.out.println("selectedProjectId.toString()..........."+selectedProjectId.toString());
		if(ValidationUtil.isEmpty(selectedProjectId.toString() , "Project", "", FacesContext.getCurrentInstance()) != null || ValidationUtil.isNonZero(selectedProjectId, "Project ", "", FacesContext.getCurrentInstance()) != null)
		{
			System.out.println("selectedProjectId.toString()...111111111........"+selectedProjectId.toString());
		FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(String.valueOf(projectAssignmentDetail.getDailyAllowance()), "Daily Allowance(INR) ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(String.valueOf(projectAssignmentDetail.getAdvanceAmount()), "Advance Amount(INR) ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(projectAssignmentDetail.getAdvanceByDate() != null ? projectAssignmentDetail.getAdvanceByDate().toString() :null , "Advance Amount By Date ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(projectAssignmentDetail.getPaymentCycleDate() != null ? projectAssignmentDetail.getPaymentCycleDate().toString() :null , "Payment Cycle [Date of every month] ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(String.valueOf(projectAssignmentDetail.getAdditionals()), "Additionals ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(String.valueOf(projectAssignmentDetail.getRoomRentAdvance()), "Room Rent Advance ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(String.valueOf(projectAssignmentDetail.getRoomRentPerMonth()), "Room Rent Per Month ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(String.valueOf(projectAssignmentDetail.getTotalAdvance()), "Total Amount ", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		
		System.out.println("Finally FORM_VALID is :::::"+FORM_VALID);
	}

	//Email Functionality
	public String sendMessage(){
		Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
		String domainName = context.getInitParameter("domainName");
		
		if(hostsMap.get(CommonLookup.DEV_EMAIL) == null){
			String[] to = {selectedProject.getOwner().getEmail()};
			emailUtil.setRecieverAddresses(to);
		}else{
			String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
			emailUtil.setRecieverAddresses(to);
		}
		
		String requestURL = "ac/project/approvedomesticprojectassignment.html";
		String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName + "/" + requestURL+"?projectAssignmentId="+projectAssignment.getProjectAssignmentId();
		String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST) + "/"	+ domainName + "/" + requestURL+"?projectAssignmentId="+projectAssignment.getProjectAssignmentId();
		String messageString = "Dear " + selectedProject.getOwner().getFirstName() + " " + selectedProject.getOwner().getLastName() + ",<br /><br />" + 
					"<a style='color:#FF9933;font-weight: bold;' href=\""+
					privateLink + "\">" + "Please click here to approve/reject domestic project assignment"+" "+projectAssignment.getProjectAssignmentCode() + "</a /><br /><br />"+
					"(Employees who are in Hyderabad office)"+"<br /><br />"+
					"<a style='color:#FF9933;font-weight: bold;' href=\""+
					publicLink + "\">" + "Please click here to approve/reject domestic project assignment"+" "+projectAssignment.getProjectAssignmentCode() + "</a /><br />"+
					"(Out side of Hyderabad office)"+"<br /><br />"+

				    "Thanks & Regards, <br />"
				    + CommonLookup.WAM_DEVTEAM_SIGNATURE;
		 
		emailUtil.setMessage(messageString);
		emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
		emailUtil.setSubject("Domestic project assignment request-"+projectAssignment.getProjectAssignmentCode());

		SwingWorker worker = new SwingWorker<String, Object>() {
			@Override
			protected String doInBackground() throws Exception {
				EMAIL_MESSAGE = emailUtil.processAndSendEmail();
				return null;
			}

			@Override
			protected void done() {
					System.out.println("DONE " + EMAIL_MESSAGE);		
			}
		};
		worker.execute();
		System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
		return EMAIL_MESSAGE;
	}
	
	
	//GETTERS AND SETTERS
	public WAMUser getWamUser() {
		return wamUser;
	}
	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}


	public String getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}


	public String getContactNumber() {
		return contactNumber;
	}
	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}
	
	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
   public Map<String, Long> getProjectsMap() {
		return projectsMap;
	}

  public void setProjectsMap(Map<String, Long> projectsMap) {
		this.projectsMap = projectsMap;
	}
	public ProjectDAO getProjectDAO() {
		return projectDAO;
	}


	public void setProjectDAO(ProjectDAO projectDAO) {
		this.projectDAO = projectDAO;
	}


	public List<Project> getProjects() {
		return projects;
	}


	public void setProjects(List<Project> projects) {
		this.projects = projects;
	}


	public Long getSelectedProjectId() {
		return selectedProjectId;
	}


	public void setSelectedProjectId(Long selectedProjectId) {
		this.selectedProjectId = selectedProjectId;
	}


	public String getApprovedBy() {
		return approvedBy;
	}


	public void setApprovedBy(String approvedBy) {
		this.approvedBy = approvedBy;
	}


	public Employee getReportingManager() {
		return reportingManager;
	}


	public void setReportingManager(Employee reportingManager) {
		this.reportingManager = reportingManager;
	}
	public RRFDAO getRrfDAO() {
		return rrfDAO;
	}


	public void setRrfDAO(RRFDAO rrfDAO) {
		this.rrfDAO = rrfDAO;
	}
	public Project getSelectedProject() {
		return selectedProject;
	}
	public void setSelectedProject(Project selectedProject) {
		this.selectedProject = selectedProject;
	}

	public ProjectAssignment getProjectAssignment() {
		return projectAssignment;
	}

	public void setProjectAssignment(ProjectAssignment projectAssignment) {
		this.projectAssignment = projectAssignment;
	}
	public ProjectAssignmentDAO getProjectAssignmentDAO() {
		return projectAssignmentDAO;
	}

	public void setProjectAssignmentDAO(ProjectAssignmentDAO projectAssignmentDAO) {
		this.projectAssignmentDAO = projectAssignmentDAO;
	}

	public ProjectAssignmentDetail getProjectAssignmentDetail() {
		return projectAssignmentDetail;
	}

	public void setProjectAssignmentDetail(ProjectAssignmentDetail projectAssignmentDetail) {
		this.projectAssignmentDetail = projectAssignmentDetail;
	}
	public String getProjectAssignmentCode() {
		return projectAssignmentCode;
	}

	public void setProjectAssignmentCode(String projectAssignmentCode) {
		this.projectAssignmentCode = projectAssignmentCode;
	}

	public String getAdditionals() {
		return additionals;
	}

	public void setAdditionals(String additionals) {
		this.additionals = additionals;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public boolean isFORM_VALID() {
		return FORM_VALID;
	}

	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Float getAdvanceAmount() {
		return advanceAmount;
	}

	public void setAdvanceAmount(Float advanceAmount) {
		this.advanceAmount = advanceAmount;
	}

	public Float getRoomRentAdvance() {
		return roomRentAdvance;
	}

	public void setRoomRentAdvance(Float roomRentAdvance) {
		this.roomRentAdvance = roomRentAdvance;
	}

	public EmployeeAndReporting getEmployeeAndReporting() {
		return employeeAndReporting;
	}

	public void setEmployeeAndReporting(EmployeeAndReporting employeeAndReporting) {
		this.employeeAndReporting = employeeAndReporting;
	}

	public Long getReportingManagerId() {
		return reportingManagerId;
	}

	public void setReportingManagerId(Long reportingManagerId) {
		this.reportingManagerId = reportingManagerId;
	}
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public EmailUtil getEmailUtil() {
		return emailUtil;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	public ServletContext getContext() {
		return context;
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}

	public String getEMAIL_MESSAGE() {
		return EMAIL_MESSAGE;
	}

	public void setEMAIL_MESSAGE(String eMAIL_MESSAGE) {
		EMAIL_MESSAGE = eMAIL_MESSAGE;
	}

	public EmployeeAndReportingDAO getEmployeeAndReportingDAO() {
		return employeeAndReportingDAO;
	}

	public void setEmployeeAndReportingDAO(
			EmployeeAndReportingDAO employeeAndReportingDAO) {
		this.employeeAndReportingDAO = employeeAndReportingDAO;
	}


}
